using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Collections.Generic;
using CreditAgricole.Framework;

namespace CreditAgricole.CommonElements.Features.CA_Production_Deployments_List
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("6d71df9d-1574-47c8-bf0a-985123116f76")]
    public class CA_Production_Deployment_ListEventReceiver : SPFeatureReceiver
    {
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            CALoggingHelper.AddInformationEntry(string.Format("Feature {0} ({1}) activated.", properties.Feature.Definition.DisplayName, properties.Feature.DefinitionId));            
            
            SPWeb web = properties.Feature.Parent as SPWeb;

            if (web != null)
            {
                bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
                web.AllowUnsafeUpdates = true;

                // Create Approvers Groups Lvl 1 & 2 if not presents
                if (SPHelper.SearchGroup(Constants.MEPApproversLvl1GroupName, web) == null)
                {
                    web.SiteGroups.Add(Constants.MEPApproversLvl1GroupName, web.Author, web.Author, Constants.MEPApproversLvl1GroupDescription);
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} created.", Constants.MEPApproversLvl1GroupName));
                }
                else
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} already exists.", Constants.MEPApproversLvl1GroupName));            


                if (SPHelper.SearchGroup(Constants.MEPApproversLvl2GroupName, web) == null)
                {
                    web.SiteGroups.Add(Constants.MEPApproversLvl2GroupName, web.Author, web.Author, Constants.MEPApproversLvl2GroupDescription);
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} created.", Constants.MEPApproversLvl2GroupName));
                }
                else
                    CALoggingHelper.AddInformationEntry(string.Format("Group {0} already exists.", Constants.MEPApproversLvl2GroupName));

                try
                {
                    SPGroup grp = web.SiteGroups[Constants.MEPApproversLvl1GroupName];
                    if (grp.OnlyAllowMembersViewMembership)
                    {
                        grp.OnlyAllowMembersViewMembership = false;
                        grp.Update();
                        CALoggingHelper.AddInformationEntry(string.Format("Visibility of membership set to Everyone for group '{0}'.", Constants.MEPApproversLvl1GroupName));
                    }
                    grp = web.SiteGroups[Constants.MEPApproversLvl2GroupName];
                    if (grp.OnlyAllowMembersViewMembership)
                    {
                        grp.OnlyAllowMembersViewMembership = false;
                        grp.Update();
                        CALoggingHelper.AddInformationEntry(string.Format("Visibility of membership set to Everyone for group '{0}'.", Constants.MEPApproversLvl2GroupName));
                    }
                }
                catch(SPException ex)
                {
                    CALoggingHelper.AddErrorEntry(ex.Message);
                }
                finally
                {
                    web.Update();
                }
                
                SPDocumentLibrary doclib = web.Lists[Constants.ChangingListTitle] as SPDocumentLibrary;
                if (doclib != null)
                {
                    // Hide title field (replaced by custom title, required)
                    SPHelper.HideField(doclib, "Title");

                    // Change Group filter for ApproverLvl1 field
                    SPGroup grp = SPHelper.SearchGroup(Constants.MEPApproversLvl1GroupName, web);
                    if (grp != null)
                    {
                        SPFieldUser approver = null;

                        try
                        {
                            approver = doclib.Fields.GetFieldByInternalName(Constants.FirstApproverField) as SPFieldUser;
                        }
                        catch { }

                        if (approver != null)
                        {
                            approver.SelectionGroup = grp.ID;
                            approver.SelectionMode = SPFieldUserSelectionMode.PeopleOnly;
                            approver.Update();
                            CALoggingHelper.AddInformationEntry(string.Format("The {0} field has been associated with \"{1}\" group.", approver.InternalName, grp.Name));
                        }
                        else
                        {
                            CALoggingHelper.AddWarningEntry(string.Format("The {0} field cannot be found.", approver.InternalName, doclib.Title));
                        }
                    }

                    // Change Group filter for ApproverLvl2 field
                    grp = SPHelper.SearchGroup(Constants.MEPApproversLvl2GroupName, web);
                    if (grp != null)
                    {
                        SPFieldUser approver = null;

                        try
                        {
                            approver = doclib.Fields.GetFieldByInternalName(Constants.SecondApproverField) as SPFieldUser;
                        }
                        catch { }

                        if (approver != null)
                        {
                            approver.SelectionGroup = grp.ID;
                            approver.SelectionMode = SPFieldUserSelectionMode.PeopleOnly;
                            approver.Update();
                            CALoggingHelper.AddInformationEntry(string.Format("The {0} field has been associated with \"{1}\" group.", approver.InternalName, grp.Name));
                        }
                        else
                        {
                            CALoggingHelper.AddWarningEntry(string.Format("The {0} field cannot be found.", approver.InternalName, doclib.Title));
                        }
                    }

                    doclib.EnableFolderCreation = false; // Disable folder creation for this document library
                    CALoggingHelper.AddInformationEntry(string.Format("Folder creation disabled for {0} list.", doclib.Title));
                    doclib.ContentTypesEnabled = false; // Disable content types for this document library (hide the content type choice drop down)
                    CALoggingHelper.AddInformationEntry(string.Format("Content type disabled for {0} list.", doclib.Title));

                    // Create calendar view
                    // CAUTION : This view will fail to open until at least on document is created in the library, because
                    // it's filtered on the workflow status and this field is only created when the first document is uploaded
                    SPView calView = null;

                    try
                    {
                        // Check if calendar view already exists
                        calView = doclib.Views[Constants.MEPCalendarViewName];
                    }
                    catch //(Exception ex)
                    {
                        //CALoggingHelper.AddErrorEntry(ex.Message);
                    }

                    if (calView == null)
                    {
                        System.Collections.Specialized.StringCollection viewFields = new System.Collections.Specialized.StringCollection();
                        viewFields.Add(Constants.DueDateField); // From
                        viewFields.Add(Constants.DueDateField); // To
                        viewFields.Add("FileLeafRef");

                        // Calendar filtered on workflow status (doc must be approved to appear in the calendar)
                        string query = @"<Where>
                                            <And>
                                                <DateRangesOverlap>
                                                    <FieldRef Name=""CADueDate"" />
                                                    <FieldRef Name=""CADueDate"" />
                                                    <Value Type=""DateTime"">
                                                        <Month />
                                                    </Value>
                                                </DateRangesOverlap>
                                                <Eq>
                                                    <FieldRef Name=""Approbat"" />
                                                    <Value Type=""WorkflowStatus"">16</Value>
                                                </Eq>
                                            </And>
                                        </Where>";

                        calView = doclib.Views.Add(Constants.MEPCalendarViewName, viewFields, query, 0, true, false, SPViewCollection.SPViewType.Calendar, false);

                        calView.ViewData = @"<FieldRef Name=""CATitle"" Type=""CalendarMonthTitle"" />
                                            <FieldRef Name=""CATitle"" Type=""CalendarWeekTitle"" />
                                            <FieldRef Name="""" Type=""CalendarWeekLocation"" />
                                            <FieldRef Name=""CATitle"" Type=""CalendarDayTitle"" />
                                            <FieldRef Name="""" Type=""CalendarDayLocation"" />";
                        calView.Update();
                    }

                    doclib.Update();


                    SPList historyList = SPHelper.GetListByName(web, Constants.WorkflowHistoryList);
                    if (historyList == null)
                    {
                        historyList = SPHelper.CreateListeBasedOnTemplate(web, SPListTemplateType.WorkflowHistory, Constants.WorkflowHistoryList);
                    }

                    SPList taskList = SPHelper.GetListByName(web, Constants.WorkflowTasksList);
                    if (taskList == null)
                    {
                        taskList = SPHelper.CreateListeBasedOnTemplate(web, SPListTemplateType.Tasks, Constants.WorkflowTasksList);
                    }

                    SPHelper.AssociateWorkflowToList(web, doclib, historyList, taskList, Constants.WorkflowTemplateName, Constants.WorkflowAssociationName);
                }
                web.AllowUnsafeUpdates = allowUnsafeUpdates;
            }
        }


        // Uncomment the method below to handle the event raised before a feature is deactivated.
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            CALoggingHelper.AddInformationEntry(string.Format("Feature {0} ({1}) deactivated.", properties.Feature.Definition.DisplayName, properties.Feature.DefinitionId));
        }


        // Uncomment the method below to handle the event raised after a feature has been installed.

        //public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        //{
        //}


        // Uncomment the method below to handle the event raised before a feature is uninstalled.

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            CALoggingHelper.AddInformationEntry(string.Format("Feature {0} ({1}) uninstalled.", properties.Feature.Definition.DisplayName, properties.Feature.DefinitionId));
        }

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}
    }
}
